package com.journey.service.impl;

import com.journey.api.IUserService;
import com.journey.common.ResponseCode;
import com.journey.common.ServerResponse;
import com.journey.mapper.UserMapper;
import com.journey.model.User;
import com.journey.util.NoteUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by ADMIN on 2018/3/15.
 */
@Transactional
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<String> checkLogin(String username, String password) {
        User user = userMapper.findByName(username);
        //检测用户名
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),"用户不存在");
        }
        //检测密码
        String md5_password = NoteUtil.md5(password);
        if(!user.getCnUserPassword().equals(md5_password)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),"密码不正确");
        }
        String cnUsrId = user.getCnUserId();
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getCode() , "用户名和密码正确" , cnUsrId);
    }

    @Override
    public ServerResponse<User> regist(String username, String password, String nickname) {
        //检测用户名是否被占用
        User has_user = userMapper.findByName(username);
        if(has_user != null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),"用户名被占用");
        }
        //注册
        User user = new User();
        user.setCnUserName(username);//设置用户名
        user.setCnUserNick(nickname);//设置昵称
        String md5_pwd = NoteUtil.md5(password);//密码md5加密处理
        user.setCnUserPassword(md5_pwd);//设置密码
        user.setCnUserId(NoteUtil.createId());//设置ID
        //调用userMapper保存
        userMapper.insertSelective(user);
        return ServerResponse.createBySuccessMessage(ResponseCode.SUCCESS.getCode(), "注册成功");
    }
}
